module.exports = {
    config: {
        asRouteService: true,
        routeRoot: 'stddev',
        dependencies: [
            'account',
            'forum',
        ],
    },
    data: {
        account: {
            // 账号所属的标准制修订组织，可以是多个
            StandardsOrg: { type: 'Array' },
        },
        forum_comments: {
            标委会: { type: 'String' },
            批次: { type: 'String' },
        },
    },
    i18n: {
        'en-us': {
            'module-title': 'Standards Development',
            'module-description': '',

            'module-mgmt-title': 'System Management',
            'module-mgmt-description': '',
            'module-dev-title': 'Development',
            'module-dev-description': '',
            'module-dev-1-title': 'Proposal',
            'module-dev-1-description': '',
            'module-dev-2-title': 'Project',
            'module-dev-2-description': '',
            'module-dev-3-title': 'Draft',
            'module-dev-3-description': '',
            'module-dev-4-title': 'Review',
            'module-dev-4-description': '',

            'Standard Orgs Based Data Scope': 'Standard Orgs Based Data Scope',
            'Data scope base on the Standards Organization': 'Data scope base on the Standards Organization',
        
            CompanyInfo: 'Company Info',
            CompanyName: 'Company Name',
            Avatar: 'Avatar',
        },
        'zh-cn': {
            'module-title': '标准制修订',
            'module-description': '',

            'module-mgmt-title': '系统管理',
            'module-mgmt-description': '',
            'module-dev-title': '制修订',
            'module-dev-description': '',
            'module-dev-1-title': '提议',
            'module-dev-1-description': '',
            'module-dev-2-title': '立项',
            'module-dev-2-description': '',
            'module-dev-3-title': '草案',
            'module-dev-3-description': '',
            'module-dev-4-title': '审核',
            'module-dev-4-description': '',

            'Standard Orgs Based Data Scope': '标准制修订基于标准组织的数据权限',
            'Data scope base on the Standards Organization': '标准制修订基于标准组织的数据权限',
        
            CompanyInfo: '公司信息',
            CompanyName: '公司名称',
            Avatar: '头像',
        },
    },
    hooks: {
        onModulesReady: async (app, mdl) => {
            // add company info into the user profile in Uc module
            app.modules.uc.config.infoStepsDefinition[0].Fields.push({
                Type: 'Category',
                Label: mdl.t('CompanyInfo'),
            }, {
                Type: 'String',
                Label: mdl.t('CompanyName'),
                Name: 'Profile.CompanyName',
            });

            app.addFlowActions([
                {
                    Flow: 'standards_in_dev',
                    Step: '3',
                    Action: 'view',
                    Func: () => {
                        return [
                            (req, res, next) => {
                                if(!req.params.id) {
                                    return next('route');
                                }
                        
                                res.locals.filter = {
                                    Board: 'stddev',
                                    Topic: req.params.id,
                                };

                                // users without audit permission only can see the comments by themselves
                                if(req.user.Permission !== '*' && !Object.nestValue(req.user.Permission, 'standards_in_dev.3.save.has')) {
                                    res.locals.filter.User = req.user.id;
                                }
                        
                                res.locals.fields = [
                                    'id',
                                    'User',
                                    'Content',
                                    'CommentTo',
                                    'LastUpdateDate',
                                    '批次',
                                ];
                        
                                res.locals.options = {
                                    sort: {
                                        LastUpdateDate: 1,
                                    },
                                    populate: [
                                        {
                                            path: 'User',
                                            select: 'UserName PhoneNumber Profile.Name Profile.Title Profile.NickName Profile.Avatar Profile.CompanyName',
                                        },
                                        {
                                            path: 'CommentTo',
                                            select: 'id User',
                                            populate: {
                                                path: 'User',
                                                select: 'UserName PhoneNumber Profile.Name Profile.Title Profile.NickName Profile.Avatar Profile.CompanyName',
                                            },
                                        },
                                    ],
                                };
                        
                                return next();
                            },
                            app.FindAllDocuments('forum_comments', false, (req, res) => {
                                const comments  = res.locals.data.docs;
                                const commentBatch = {};
                                const commentBatchList = [];

                                for (let i = 0; i < comments.length; i++) {
                                    const doc = comments[i];
                                    doc.User = doc.User._doc || doc.User;
                        
                                    if (!doc.User) {
                                        continue;
                                    }
                        
                                    const userCompany = doc.User.Profile && doc.User.Profile.CompanyName;
                                    const userDisplyName = (doc.User.Profile && (doc.User.Profile.NickName || doc.User.Profile.Name || doc.User.Profile.Title)) || doc.User.UserName || doc.User.PhoneNumber;
                                    doc.UserName = userCompany ? `${userCompany} - ${userDisplyName}` : userDisplyName;

                                    if(doc.User.Profile && doc.User.Profile.Avatar) {
                                        const avatar = doc.User.Profile.Avatar;
                                        doc.UserAvatar = avatar.id || avatar;
                                    }
                        
                                    delete doc.User;
                                    delete doc._id;
                        
                                    // process comment to user
                                    if(doc.CommentTo && doc.CommentTo.User) {
                                        doc.CommentTo = doc.CommentTo._doc || doc.CommentTo;
                                        doc.CommentTo.User = doc.CommentTo.User._doc || doc.CommentTo.User;

                                        const ctUserCompany = doc.CommentTo.User.Profile && doc.CommentTo.User.Profile.CompanyName;
                                        const ctUserDisplyName = (doc.CommentTo.User.Profile && (doc.CommentTo.User.Profile.NickName || doc.CommentTo.User.Profile.Name || doc.CommentTo.User.Profile.Title)) || doc.CommentTo.User.UserName || doc.CommentTo.User.PhoneNumber;
                                        doc.CommentTo.UserName = ctUserCompany ? `${ctUserCompany} - ${ctUserDisplyName}` : ctUserDisplyName;
                        
                                        if(doc.CommentTo.User.Profile && doc.CommentTo.User.Profile.Avatar) {
                                            const avatar = doc.CommentTo.User.Profile.Avatar;
                                            doc.CommentTo.UserAvatar = avatar.id || avatar;
                                        }
                        
                                        delete doc.CommentTo._id;
                                        delete doc.CommentTo.User;
                                    }

                                    // add to batch
                                    if (doc.批次) {
                                        if (commentBatchList.indexOf(doc.批次) < 0) {
                                            commentBatchList.push(doc.批次);
                                        }
                                        if (!commentBatch[doc.批次]) {
                                            commentBatch[doc.批次] = [];
                                        }
                                        commentBatch[doc.批次].push(doc);
                                    }
                                }

                                const currentBatch = res.locals.data.意见批次 || '默认批';
                                // add the current batch event there is no comment
                                if (currentBatch && commentBatchList.indexOf(currentBatch) < 0) {
                                    commentBatchList.push(currentBatch);
                                }

                                const currentBatchIdx = commentBatchList.indexOf(res.locals.data.意见批次);

                                res.addData({
                                    Comments: commentBatchList.map((batch, idx) => {
                                        return {
                                            current: idx === currentBatchIdx,
                                            Batch: batch,
                                            Comments: commentBatch[batch] || [],
                                        }
                                    }),
                                }, false);

                                delete res.locals.data.docs;
                                delete res.locals.data.total;
                                delete res.locals.data.pages;
                                delete res.locals.data.page;
                                delete res.locals.data.limit;
                            })
                        ]
                    }
                },
            ]);
        },
    },
}